<?php

class GroupController extends BaseController
{
	public function indexAction()
	{
		$groups = Group::all();
		
        $this->layout->title = 'Group listings';
        $this->layout->main = View::make('dash')->nest('content', 'groups.index', compact('groups'));
	}
	
    public function addAction()
    {
        $form = new GroupForm();

        if ($form->isPosted())
        {
            if ($form->isValidForAdd())
            {
                Group::create([
                    "name" => Input::get("name")
                ]);

                return Redirect::route("group/index");
            }

            return Redirect::route("group/add")->withInput([
                "name"   => Input::get("name"),
                "errors" => $form->getErrors()
            ]);
        }

        $this->layout->title = 'Group add';
        $this->layout->main = View::make('dash')->nest('content', 'groups.add', compact('form'));
    }

    public function editAction($id)
    {
        $form  = new GroupForm();

        //$id    = Input::get("id");
        $group = Group::findOrFail($id);
        $url   = URL::full();

        if ($form->isPosted())
        {
            if ($form->isValidForEdit())
            {
                $group->name = Input::get("name");
                $group->save();

                //$group->users()->sync(Input::get("user_id", []));
                //$group->resources()->sync(Input::get("resource_id", []));

                return Redirect::route("group/index");
            }

            return Redirect::to($url)->withInput([
                "name"   => Input::get("name"),
                "errors" => $form->getErrors(),
                "url"    => $url
            ]);
        }

//         return View::make("group/edit", [
//             "form"      => $form,
//             "group"     => $group,
//             //"users"     => User::all(),
//             //"resources" => Resource::where("secure", true)->get()
//         ]);
        
        $this->layout->title = 'Group edit';
        $this->layout->main = View::make('dash')->nest('content', 'groups.edit', compact('form', 'group'));
    }

    public function deleteAction($id)
    {
        $form = new GroupForm();

        if ($form->isValidForDelete())
        {
            $group = Group::findOrFail($id);
            $group->delete();
        }

        return Redirect::route("group/index");
    }
}